package com.beanutil.examples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.ResultSetDynaClass;

public class BeanUtilExample3 {

	@SuppressWarnings("rawtypes")
	public static void main(String[] args) {
		Connection conn = getConnection();
		String sql = "select id,title,time from guestbook";
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			ResultSetDynaClass rsdc = new ResultSetDynaClass(rs);
			// ResultSetDynaClass将ResultSet进行2次封装
			// 每条结果被封装成了DynaBean类型的javabean对象
			// rsdc和Connection有依赖关系，若Connection被关闭则不能再从rsdc读数据
			Iterator it = rsdc.iterator();
			while (it.hasNext()) {
				DynaBean bean = (DynaBean) it.next();
				System.out.print(bean.get("id"));
				System.out.print(bean.get("title"));
				System.out.println(bean.get("time"));
			}
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private static Connection getConnection() {
		String url = "jdbc:oracle:thin:@192.168.1.2:1521:ora92";
		String username = "scott";
		String password = "tiger";
		Connection conn = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
}
